import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import { useDispatch } from 'react-redux';
import { getArticleActionCreator } from '@/store/action/article';
import { useParams } from 'react-router-dom';
import { useAppSelector } from './../../store/index';
import classNames from 'classnames';
import Skeleton from './components/Skeleton';
import dayjs from 'dayjs';
import DOMPurify from 'dompurify';
import { getCommentActionCreator } from '@/store/action/comment';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import ArticleFooter from './components/ArticleFooter';
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';
import { Popup } from 'antd-mobile';
import CommentInput from './components/CommentInput';
import { changeUserFollowActionCreator } from '@/store/action/user';
import Share from './components/Share';

export default function Artile() {
  const dispatch = useDispatch();
  // 通过params获取路由传递的参数
  // 🔔 useParams 函数需要指定泛型确定 params 对象的格式
  const params = useParams<{ id: string }>();

  // 从redux中获取文章详情数据
  const { detail } = useAppSelector((state) => state.articleList);
  // console.log('文章详情数据', 18, detail);

  // 从redux中获取文章评论数据
  const { comments } = useAppSelector((state) => state.comment);
  // console.log('评论数据', 27, comments);

  // 进入页面获取文章数据
  useEffect(() => {
    dispatch(getArticleActionCreator(params.id));
  }, [dispatch, params.id]);

  useEffect(() => {
    if (!detail.art_id) return;
    // eslint-disable-next-line react-hooks/exhaustive-deps
    // 加载完毕，需要高亮处理
    hljs.configure({
      // 忽略未经转义的Html字符
      ignoreUnescapedHTML: true,
    });

    // 查找容器元素下符合precode选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length > 0) {
      return codes.forEach((el: any) => hljs.highlightElement(el));
    }

    // 查找容器元素下的 pre 元素，进行高亮
    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      return pre.forEach((el: any) => hljs.highlightElement(el));
    }
  }, [detail.art_id]);

  // 作者信息
  const [showAuthor, setShowAuthor] = useState(false);
  const authorRef = useRef<HTMLDivElement>(null);
  // 滚动事件处理函数
  const handleScroll = () => {
    // 获取元素在可视区的滚动距离
    // 普通非空断言
    // console.log(68, authorRef.current);

    if ((authorRef.current as HTMLDivElement).getBoundingClientRect().y < 0) {
      // 非空断言简写，感叹号
      // if (authorRef.current!.getBoundingClientRect().y < 0) {
      setShowAuthor(true);
    } else {
      showAuthor && setShowAuthor(false);
    }
  };

  //进入页面获取文章的评论列表
  useEffect(() => {
    dispatch(getCommentActionCreator({ type: 'a', source: params.id }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch]);

  const wrapperRef = useRef<HTMLDivElement>(null);
  const commentHeadRef = useRef<HTMLDivElement>(null);

  // 准备开关变量，用于切换是否滚动到评论区
  const isShowComment = useRef(false);
  const onShowComment = () => {
    isShowComment.current = !isShowComment.current;
    // 计算评论区的距离
    const top =
      commentHeadRef.current!.offsetTop - commentHeadRef.current!.offsetHeight;

    wrapperRef.current?.scrollTo({
      // 通过开关思想，切换滚动到评论区和返回顶部
      top: isShowComment.current ? top : 0,
    });
  };

  // 分享功能
  const [share, setShare] = useState(false);
  const onCloseShare = () => {
    setShare(false);
  };

  // 关注功能
  const handleFollow = async () => {
    // 调用关注action
    await dispatch(changeUserFollowActionCreator(detail.aut_id));
  };

  // 添加评论的显示和隐藏
  const [showComment, setShowComment] = useState(false);
  const closeComment = () => {
    setShowComment(false);
  };
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {showAuthor ? (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                onClick={handleFollow}
                className={classNames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}
              >
                {detail.is_followed ? '已关注' : '+关注'}
              </span>
            </div>
          ) : (
            <>文章详情</>
          )}
          {/* <div className="nav-author">
            <img src={detail.aut_photo} alt="" />
            <span className="name">{detail.aut_name}</span>
            <span
              className={classNames(
                'follow',
                detail.is_followed ? 'followed' : ''
              )}
            >
              {detail.is_followed ? '已关注' : '+关注'}
            </span>
          </div>
          <>文章详情</> */}
        </NavBar>
        {/* 文章主体 */}
        <div className="wrapper" ref={wrapperRef} onScroll={handleScroll}>
          <div className="article-wrapper" hidden={!!detail.art_id}>
            {/* 骨架屏占位效果 */}
            <Skeleton />
          </div>
          <div className="article-wrapper" hidden={!detail.art_id}>
            {/* 文章描述信息栏 */}
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>
                  {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
                  {/* {dayjs().from(detail.pubdate)} */}
                </span>
                <span>{10} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              {/* 作者信息 - 滚动出去到可视区外，头部显示作者信息*/}
              <div className="author" ref={authorRef}>
                <img src={detail.aut_photo} alt="" />
                <span className="name">{detail.aut_name}</span>
                <span
                  onClick={handleFollow}
                  className={classNames(
                    'follow',
                    detail.is_followed ? 'followed' : ''
                  )}
                >
                  {detail.is_followed ? '已关注' : '+关注'}
                </span>
              </div>
            </div>

            {/* 文章正文内容区域 */}
            <div className="content">
              <div
                className="content-html dg-html"
                // 💥 dompurify.sanitize() 对 HTML 内容进行净化，防止 XSS 攻击
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(detail.content),
                }}
              />
              <div className="date">
                发布文章时间：
                {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
                {/* {dayjs().from(detail.pubdate)} */}
              </div>
            </div>
            <div className="divider"></div>
            <div className="comment">
              {/* 评论总览信息 */}
              <div className="comment-header" ref={commentHeadRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>

              {/* 评论列表 */}
              {comments.results?.length === 0 ? (
                <NoComment />
              ) : (
                comments.results?.map((item) => (
                  <CommentItem key={item.com_id} comment={item} />
                ))
              )}
            </div>
          </div>
        </div>
        {/* 文章底部 */}
        <ArticleFooter
          onShowComment={onShowComment}
          onComment={() => setShowComment(true)}
          onShare={() => setShare(true)}
        />
        {/* 分享抽屉 */}
        <Popup
          position="bottom"
          bodyStyle={{ backgroundColor: 'transparent' }}
          visible={share}
          onMaskClick={onCloseShare}
        >
          <Share onClose={onCloseShare} />
        </Popup>
        {/* 评论弹框 */}
        <Popup
          className="drawer"
          position="bottom"
          visible={showComment}
          onMaskClick={closeComment}
        >
          {showComment && <CommentInput onClose={closeComment} />}
        </Popup>
      </div>
    </div>
  );
}
